import { defineStore } from 'pinia';
import { ref } from 'vue';

export interface UserState {
  token: string | null;
  isLoggedIn: boolean;
  userInfo: {
    id?: number;
    username?: string;
    nickname?: string;
    avatar?: string;
    phone?: string;
    email?: string;
    gender?: string;
    age?: number;
    role?: string;
  } | null;
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('token'));
  const userInfo = ref<UserState['userInfo']>(null);
  const isLoggedIn = ref(!!token.value);

  // 加载用户信息
  const loadUserInfo = () => {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo);
      } catch (error) {
        console.error('Parse userInfo failed', error);
      }
    }
  };

  // 设置用户信息
  const setUserInfo = (info: UserState['userInfo']) => {
    userInfo.value = info;
    if (info) {
      localStorage.setItem('userInfo', JSON.stringify(info));
    } else {
      localStorage.removeItem('userInfo');
    }
  };

  // 设置登录状态
  const setLoginState = (loggedIn: boolean, newToken?: string) => {
    isLoggedIn.value = loggedIn;
    
    if (loggedIn && newToken) {
      token.value = newToken;
      localStorage.setItem('token', newToken);
    } else {
      token.value = null;
      localStorage.removeItem('token');
    }
  };

  // 登录
  const login = (newToken: string, info: UserState['userInfo']) => {
    setLoginState(true, newToken);
    setUserInfo(info);
  };

  // 退出登录
  const logout = () => {
    setLoginState(false);
    setUserInfo(null);
  };

  // 初始化 - 自动从localStorage加载用户信息
  loadUserInfo();

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    setUserInfo
  };
});
